import React from 'react'
import style from './style'
import cx from 'classnames'

export default 
class Tabs extends React.Component {

  state = {}

  handleClick(e, v, i) {
    if (!v.disabled) {
      this.props.onChange(i+1)
    }
  }

  getPos(props) {
    props = props || this.props
    const { index } = props
    const el = this.el.children[index-1]
    const { width, left } = el.getBoundingClientRect()
    this.setState({
      left: left - this.left,
      width
    })
  }

  componentDidMount() {
    this.el = this.refs.ul
    this.left = this.el.getBoundingClientRect().left
    this.getPos()
  }

  componentWillReceiveProps(props) {
    if (props.index != this.props.index) {
      this.getPos(props)
    }
  }
  _getPos(props) {
    if(!this.el) return {};
    props = props || this.props
    const { index } = props
    const el = this.el.children[index-1]
    const { width, left } = el.getBoundingClientRect()
    return {
      left: left - this.left,
      width
    };
  }
  render() {
    const { className, tabs, top, index, onChange } = this.props
    if (!tabs.length) return null

    const { left, width } = this._getPos();
    return (
      <ul 
        data-role="tabs"
        ref='ul' 
        className={cx(
          style.root,
          {
            [style.top]: top,
            [style.bottom]: !top,
            [className]: className
          }
        )}
      >
        {
          tabs.map((v, i) => (
            <li 
              className={cx({
                [style.active]: index == i+1,
                [style.disabled]: v.disabled
              })}
              key={i}
              onClick={e => this.handleClick(e, v, i)}
            >{ v.label }</li>
          ))
        }
        <b 
          style={{
            width: width !== null? (width + 'px'): 'auto',
            left: left !== null? (left + 'px'): 'auto'
          }}
          className={style.indicator}/>
      </ul>
    )
  }
}
